import { _decorator, Component, Node, Prefab, instantiate, randomRangeInt, Size, view, v3, math, find } from 'cc';
import { GameConfig } from './config/GameConfig';
const { ccclass, property } = _decorator;

/**
 * 
 * 子弹buff 和 boom buff 管理器
 * 
 */

@ccclass('BuffFactory')
export class BuffFactory extends Component {

    @property(Prefab)
    bulletBuf: Prefab;

    @property(Prefab)
    BoomBuf: Prefab;

    viewSize: Size;

    buffs: Node;

    start() {
        this.viewSize = view.getVisibleSize()

        this.buffs = find('Canvas/buffs')

        this.generateBuff()
    }

    update(deltaTime: number) {

    }


    /**
     * 
     * 生成buff: 每5s 判断0 / 1 生成一次
     * 
     * 子弹 每10 - 20 s 生成一次
     * 炸弹 每10 - 20 s 生成一次
     * 
     */
    generateBuff() {
        this.generateBulletDelay()
        this.generateBoomDelay()
    }
    generateBulletDelay() {
        this.scheduleOnce(() => {
            this.generateBullet()
            this.generateBulletDelay()
        }, randomRangeInt(GameConfig.bufferBulletGenerateTime[0], GameConfig.bufferBulletGenerateTime[1]))
    }
    generateBullet() {
        let bullet = instantiate(this.bulletBuf)
        bullet.setPosition(this.getRandomPositon())
        bullet.setParent(this.buffs)
    }
    generateBoomDelay() {
        this.scheduleOnce(() => {
            this.generateBoom()
            this.generateBoomDelay()
        }, randomRangeInt(GameConfig.bufferBoomGenerateTime[0], GameConfig.bufferBoomGenerateTime[1]))
    }
    generateBoom() {
        let boom = instantiate(this.BoomBuf)
        boom.setPosition(this.getRandomPositon())
        boom.setParent(this.buffs)
    }


    /**
     * 获取一个随机位置
     * @param width 
     * @returns 
     */
    getRandomPositon(width: number = 100) {
        // x 不超过可攻击范围
        let tmp = this.viewSize.width / 2 - width / 2
        return v3(math.randomRange(-tmp, tmp), 450 + randomRangeInt(0, 50))
    }

}


